package com.ccut.xunfeiSpringboot.controller;

import com.ccut.xunfeiSpringboot.common.AjaxResult;
import com.ccut.xunfeiSpringboot.dto.LoginRequest;
import com.ccut.xunfeiSpringboot.entity.Admin;
import com.ccut.xunfeiSpringboot.entity.School;
import com.ccut.xunfeiSpringboot.entity.Student;
import com.ccut.xunfeiSpringboot.service.SchoolService;
import com.ccut.xunfeiSpringboot.service.StudentService;
import com.ccut.xunfeiSpringboot.service.AdminService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import com.ccut.xunfeiSpringboot.utils.JwtUtils;

import static org.springframework.util.StringUtils.hasText;

@RestController
@RequestMapping("/api")
public class WebController {
    @Resource
    private StudentService studentService;

    @Resource
    private AdminService adminService;

    @Resource
    private SchoolService schoolService;

    @GetMapping("/hello")
    public String hello() {
        return "Hello";
    }

    /**
     * 登录接口（顺序查询学生表和管理员表）
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginRequest loginRequest) {
        try {
            if ("student".equals(loginRequest.getRole())) {
                Student student = studentService.login(loginRequest.getUsername());
                if (student != null) {
                    if (!loginRequest.getPassword().equals(student.getPassword())) {
                        return AjaxResult.error("用户名或密码错误", 401);
                    }
                    Map<String, Object> claims = new HashMap<>();
                    claims.put("id", student.getId());
                    claims.put("username", student.getUsername());
                    claims.put("role", "student");
                    String token = JwtUtils.generateToken(claims);
                    if (userInfoComplete(student)) {
                        // 登录成功且信息完整
                        return AjaxResult.success("登录成功")
                                .put("token", token)
                                .put("businessStatus", 0);
                    } else {
                        // 登录成功但信息不完整
                        return AjaxResult.success("信息不完整，请补全资料", 200)
                                .put("token", token)
                                .put("businessStatus", 1);
                    }
                }
            } else if ("admin".equals(loginRequest.getRole())) {
                Admin admin = adminService.login(loginRequest.getUsername(), loginRequest.getPassword());
                if (admin != null) {
                    Map<String, Object> claims = new HashMap<>();
                    claims.put("id", admin.getId());
                    claims.put("username", admin.getUsername());
                    claims.put("role", "admin");
                    String token = JwtUtils.generateToken(claims);
                    return AjaxResult.success("登录成功")
                            .put("token", token)
                            .put("businessStatus", 0);
                }
            }else if("school".equals(loginRequest.getRole())){
                System.out.println("1234");
                School school = schoolService.login(loginRequest.getUsername());
                if (school != null) {
                    Map<String, Object> claims = new HashMap<>();
                    claims.put("id", school.getSchoolId());
                    claims.put("username", school.getUsername());
                    claims.put("role", "school");
                    String token = JwtUtils.generateToken(claims);

                    if (schoolInfoComplete(school)) {
                        //高校管理员登录成功且信息完整
                        return AjaxResult.success("登录成功")
                                .put("token", token)
                                .put("businessStatus", 0);
                    } else {
                        // 高校管理员信息不完整
                        return AjaxResult.success("高校信息不完整", 201)
                                .put("token", token)  // ✅ 添加这一行
                                .put("businessStatus", 1);
                    }
                }
            }
            // 用户名或密码错误
            return AjaxResult.error("用户名或密码错误", 401);
        } catch (Exception e) {
            return AjaxResult.error("登录失败: " + e.getMessage(), 500);
        }
    }
    // 辅助方法：判断学生信息是否完整
    private boolean userInfoComplete(Student student) {
        return student != null
                && hasText(student.getUsername())
                && hasText(student.getPassword())
                && hasText(student.getName())
                && hasText(student.getSex())
                && hasText(student.getEmail())
                && hasText(student.getTelephone())
                && hasText(student.getEducationBackground())
                && hasText(student.getInternshipExperience())
                && hasText(student.getCampusExperience())
                && hasText(student.getSkills())
                && hasText(student.getSelfEvaluation())
                && hasText(student.getTechCompetition())
                && student.getRecord() != null
                && student.getSalary() != null
                && hasText(student.getCity())
                && hasText(student.getBenefits())
                && hasText(student.getOfficeHours());
    }
    /**
     * 辅助方法：判断高校管理员信息是否完整
     */
    private boolean schoolInfoComplete(School school) {
        return school != null
                && hasText(school.getSchoolName())
                && hasText(school.getAddress())
                && hasText(school.getContactNumber())
                && hasText(school.getPrincipal())
                && school.getEstablishedYear() != null;
    }

    /**
     * 注册接口
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody Map<String, String> request) {
        String role = request.get("role"); // 获取角色标识：student 或 admin
        String username = request.get("username");
        String password = request.get("password");
        String confirmPassword = request.get("confirmPassword");
        // 处理学生注册
        if ("student".equals(role)) {
            if (studentService.existsByUsername(username)) {
                return AjaxResult.error("该学生用户名已存在");
            }
            Student student = new Student();
            student.setUsername(username);
            student.setPassword(password);
            student.setRegisterTime(Timestamp.valueOf(LocalDateTime.now()).toLocalDateTime());
            studentService.register(student);
            return AjaxResult.success();
        }
         //处理高校管理员注册
        else if ("school".equals(role)) {
            if (schoolService.existsByUsername(username)) {
                return AjaxResult.error("该企业用户名已存在");
            }
            School school = new School();
            school.setUsername(username);
            school.setPassword(password);
            schoolService.register(school);
            return AjaxResult.success("高校管理员注册成功", 200);
        }
        else {
            return AjaxResult.error("无效的角色类型");
        }
    }
    @PutMapping("/student/update")
    public AjaxResult updateUserInfo(@RequestBody Map<String, Object> request) {
        Integer id = (Integer) request.get("id");

        Student student = studentService.selectById(id);
        if (student == null) {
            return AjaxResult.error("用户不存在");
        }
        try {
            student.setName((String) request.get("name"));
            student.setUsername((String) request.get("username"));
            student.setPassword((String) request.get("password"));
            student.setSex((String) request.get("sex"));
            student.setEmail((String) request.get("email"));
            student.setTelephone((String) request.get("telephone"));
            student.setEducationBackground((String) request.get("educationBackground"));
            student.setSkills((String) request.get("skills"));
            student.setInternshipExperience((String) request.get("internshipExperience"));
            student.setCampusExperience((String) request.get("campusExperience"));
            student.setTechCompetition((String) request.get("techCompetition"));
            student.setSelfEvaluation((String) request.get("selfEvaluation"));
            student.setRecord(toInteger(request.get("record")));
            student.setSalary(toInteger(request.get("salary")));
            String city = (String) request.get("city");
            if (city != null && !city.isEmpty()) {
                student.setCity(city);
            }
            student.setBenefits((String) request.get("benefits"));
            String officeHours = (String) request.get("officeHours");
            if (officeHours != null && !officeHours.isEmpty()) {
                student.setOfficeHours(officeHours);
            }
            student.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()).toLocalDateTime());
            studentService.update(student);
            return AjaxResult.success("更新成功");
        } catch (Exception e) {
            return AjaxResult.error("更新失败：" + e.getMessage(), 500);
        }
    }
    @PutMapping("/school/update")
    public AjaxResult updateSchoolInfo(@RequestBody Map<String, Object> request) {
        Integer id = (Integer) request.get("id");
        School school = schoolService.selectById(id);
        if (school == null) {
            return AjaxResult.error("学校不存在");
        }
        try {
            school.setSchoolName((String) request.get("schoolName"));
            school.setAddress((String) request.get("address"));
            school.setContactNumber((String) request.get("contactNumber"));
            school.setPrincipal((String) request.get("principal"));
            school.setEstablishedYear(toInteger(request.get("establishedYear")));
            school.setDescription((String) request.get("description"));
            school.setUpdatedAt(Timestamp.valueOf(LocalDateTime.now()));
            schoolService.update(school);
            return AjaxResult.success("更新成功");
        } catch (Exception e) {
            return AjaxResult.error("更新失败：" + e.getMessage(), 500);
        }
    }

    @PutMapping("/admin/update")
    public AjaxResult updateadminAdminInfo(@RequestBody Map<String, Object> request) {
        Integer id = (Integer) request.get("id");

        Admin admin = adminService.selectById(id);
        if (admin == null) {
            return AjaxResult.error("管理员不存在");
        }

        try {
            adminService.update(admin);
            return AjaxResult.success("更新成功");
        } catch (Exception e) {
            return AjaxResult.error("更新失败：" + e.getMessage(), 500);
        }
    }
    private Integer toInteger(Object obj) {
        if (obj == null) return null;
        if (obj instanceof Integer) {
            return (Integer) obj;
        } else if (obj instanceof String && !((String) obj).trim().isEmpty()) {
            try {
                return Integer.parseInt((String) obj);
            } catch (NumberFormatException ignored) {}
        }
        return null;
    }
    @GetMapping("/student/info/{id}")
    public AjaxResult getStudentInfo(@PathVariable Integer id) {
        Student student = studentService.selectById(id);
        if (student == null) {
            return AjaxResult.error("用户不存在");
        }

        Map<String, Object> data = new HashMap<>();
        data.put("username", student.getUsername());
        data.put("password", student.getPassword());
        data.put("name", student.getName());
        data.put("sex", student.getSex());
        data.put("email", student.getEmail());
        data.put("telephone", student.getTelephone());
        data.put("educationBackground", student.getEducationBackground());
        data.put("skills", student.getSkills());
        data.put("internshipExperience", student.getInternshipExperience());
        data.put("campusExperience", student.getCampusExperience());
        data.put("techCompetition", student.getTechCompetition());
        data.put("selfEvaluation", student.getSelfEvaluation());
        data.put("record", student.getRecord());
        data.put("salary", student.getSalary());
        data.put("city", student.getCity());
        data.put("benefits", student.getBenefits());
        data.put("officeHours", student.getOfficeHours());
        data.put("registerTime", formatDate(student.getRegisterTime()));
        data.put("updateTime", formatDate(student.getUpdateTime()));

        return AjaxResult.success("获取成功", data);
    }
    private String formatDate(LocalDateTime dateTime) {
        if (dateTime == null) {
            return null;
        }
        return java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dateTime);
    }
    @GetMapping("/admin/info/{id}")
    public AjaxResult getAdminInfo(@PathVariable Integer id) {
        Admin admin = adminService.selectById(id);
        if (admin == null) {
            return AjaxResult.error("用户不存在");
        }

        // 构造响应数据
        Map<String, Object> data = new HashMap<>();
        data.put("username", admin.getUsername());
        data.put("password", admin.getPassword());
        return AjaxResult.success("获取成功", data);
    }
    @GetMapping("/school/info/{id}")
    public AjaxResult getSchoolInfo(@PathVariable Integer id) {
        School school = schoolService.selectById(id);
        System.out.println("【DEBUG】学校信息：" + school);
        System.out.println("12345");
        if (school == null) {
            return AjaxResult.error("学校不存在");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("id", school.getSchoolId());
        data.put("username", school.getUsername());
        data.put("password", school.getPassword());
        data.put("schoolName", school.getSchoolName());
        data.put("address", school.getAddress());
        data.put("contactNumber", school.getContactNumber());
        data.put("principal", school.getPrincipal());
        data.put("establishedYear", school.getEstablishedYear());
        data.put("description", school.getDescription());
        data.put("createdAt", formatDate(school.getCreatedAt()));
        data.put("updatedAt", formatDate(school.getUpdatedAt()));
        return AjaxResult.success("获取成功", data);
    }


}